package com.three.lab.util;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;

/**
 * 偏好设置存储一些临时数据
 * @author liangqida on 2024-06-04.
 *
 */
public class SharedPreferencesUtils {
	
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	private static SharedPreferencesUtils sharedPreferencesUtils;
	private final static String APP_SHAREPREFERENCES_NAME = "com.three.lab.pref";

	/**
	 * 单例模式获取实例
	 * @param context
	 * @return
	 */
	public static SharedPreferencesUtils getInstances(Context context) {
		if (sharedPreferencesUtils == null) {
			synchronized (SharedPreferencesUtils.class) {
				if (sharedPreferencesUtils == null) {
					sharedPreferencesUtils = new SharedPreferencesUtils(context);
				}
			}
		}
		return sharedPreferencesUtils;
	}

	/***
	 * 构造函数
	 * @param context
	 */
	public SharedPreferencesUtils(Context context) {
		sharedPreferences = context.getSharedPreferences(APP_SHAREPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();
	}

	/**
	 * 存储
	 */
	public void put(String key, Object object) {
		if (object instanceof String) {
			editor.putString(key, (String) object);
		} else if (object instanceof Integer) {
			editor.putInt(key, (Integer) object);
		} else if (object instanceof Boolean) {
			editor.putBoolean(key, (Boolean) object);
		} else if (object instanceof Float) {
			editor.putFloat(key, (Float) object);
		} else if (object instanceof Long) {
			editor.putLong(key, (Long) object);
		} else {
			editor.putString(key, object.toString());
		}
		editor.commit();
	}

	/**
	 * 获取保存的数据
	 */
	public Object getSharedPreference(String key, Object defaultObject) {
		if (contain(key)) {
			if (defaultObject instanceof String) {
				return sharedPreferences.getString(key, (String) defaultObject);
			} else if (defaultObject instanceof Integer) {
				return sharedPreferences.getInt(key, (Integer) defaultObject);
			} else if (defaultObject instanceof Boolean) {
				return sharedPreferences.getBoolean(key, (Boolean) defaultObject);
			} else if (defaultObject instanceof Float) {
				return sharedPreferences.getFloat(key, (Float) defaultObject);
			} else if (defaultObject instanceof Long) {
				return sharedPreferences.getLong(key, (Long) defaultObject);
			} else {
				return sharedPreferences.getString(key, "");
			}
		} else {
			return defaultObject;
		}
	}

	/**
	 * 移除某个key值已经对应的值
	 */
	public void remove(String key) {
		editor.remove(key);
		editor.commit();
	}

	/**
	 * 清除所有数据
	 */
	public void clear() {
		editor.clear();
		editor.commit();
	}

	/**
	 * 查询某个key是否存在
	 */
	public Boolean contain(String key) {
		return sharedPreferences.contains(key);
	}

	/**
	 * 返回所有的键值对
	 */
	public Map<String, ?> getAll() {
		return sharedPreferences.getAll();
	}

}